<?php

namespace app\admin\controller\user;

use app\admin\controller\AuthController;
use app\admin\model\system\SystemUserLevel;
use basic\BaseModel;
use repositories\UserRepository;
use services\JsonService as Json;
use services\UtilService as Util;
use services\FormBuilder as Form;
use think\facade\Route as Url;
use traits\CurdControllerTrait;
use app\admin\model\user\{User as UserModel, UserBill as UserBillAdmin};

/**
 * @title 会员管理模块
 * Class User
 * @package app\admin\controller\user
 */
class User extends AuthController
{
    use CurdControllerTrait;

    /**
     * @title 会员的入口
     */
    public function index()
    {
        $this->assign("count_user", UserModel::getCount());
        return $this->fetch();
    }

    /*
     * 赠送会员等级
     * @paran int $uid
     * */
    public function give_level($uid = 0)
    {
        if (!$uid) return $this->failed('缺少参数');
        $level = \app\models\user\UserLevel::getUserLevel($uid);
        //获取当前会员等级
        if ($level === false)
            $grade = 0;
        else
            $grade = \app\models\user\UserLevel::getUserLevelInfo($level, 'grade');
        //查询高于当前会员的所有会员等级
        $systemLevelList = SystemUserLevel::where('grade', '>', $grade)->where(['is_show' => 1, 'is_del' => 0])->field(['name', 'id'])->select();
        $field[] = Form::select('level_id', '会员等级')->setOptions(function () use ($systemLevelList) {
            $menus = [];
            foreach ($systemLevelList as $menu) {
                $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
            }
            return $menus;
        })->filterable(1);
        $form = Form::make_post_form('赠送会员', $field, Url::buildUrl('save_give_level', ['uid' => $uid]), 2);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**
     * 获取user表
     *
     * @return json
     */
    public function get_user_list()
    {
        $where = Util::getMore([
            ['page', 1],
            ['limit', 20],
            ['nickname', ''],
            ['status', ''],
            ['pay_count', ''],
            ['is_promoter', ''],
            ['order', ''],
            ['data', ''],
            ['user_type', ''],
            ['country', ''],
            ['province', ''],
            ['city', ''],
            ['user_time_type', ''],
            ['user_time', ''],
            ['sex', ''],
        ]);
        return Json::successlayui(UserModel::getUserList($where));
    }

    /**
     * 编辑模板消息
     * @param $id
     * @return mixed|\think\response\Json|void
     */
    public function edit($uid)
    {
        if (!$uid) return $this->failed('数据不存在');
        $user = UserModel::get($uid);
        if (!$user) return Json::fail('数据不存在!');
        $f = array();
        $f[] = Form::input('uid', '用户编号', $user->getData('uid'))->disabled(1);
        $f[] = Form::input('real_name', '真实姓名', $user->getData('real_name'));
        $f[] = Form::text('phone', '手机号', $user->getData('phone'));
        $f[] = Form::date('birthday', '生日', $user->getData('birthday') ? date('Y-m-d', $user->getData('birthday')) : 0);
        $f[] = Form::input('card_id', '身份证号', $user->getData('card_id'));
        $f[] = Form::textarea('mark', '用户备注', $user->getData('mark'));
        $f[] = Form::radio('is_promoter', '推广员', $user->getData('is_promoter'))->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '关闭']]);
        $f[] = Form::radio('status', '状态', $user->getData('status'))->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '锁定']]);
        $form = Form::make_post_form('添加用户通知', $f, Url::buildUrl('update', array('uid' => $uid)), 5);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**
     * 更新会员的资料
     * @param $uid
     */
    public function update($uid)
    {
        $data = Util::postMore([
            ['money_status', 0],
            ['is_promoter', 1],
            ['real_name', ''],
            ['phone', 0],
            ['card_id', ''],
            ['birthday', ''],
            ['mark', ''],
            ['money', 0],
            ['integration_status', 0],
            ['integration', 0],
            ['status', 0],
        ]);
        if (!$uid) return $this->failed('数据不存在');
        $user = UserModel::get($uid);
        if (!$user) return Json::fail('数据不存在!');
        BaseModel::beginTrans();
        $res1 = false;
        $res2 = false;
        $edit = array();
        if ($data['money_status'] && $data['money']) {//余额增加或者减少
            if ($data['money_status'] == 1) {//增加
                $edit['now_money'] = bcadd($user['now_money'], $data['money'], 2);
                $res1 = UserBillAdmin::income('系统增加余额', $user['uid'], 'now_money', 'system_add', $data['money'], $this->adminId, $edit['now_money'], '系统增加了' . floatval($data['money']) . '余额');
                try {
                    UserRepository::adminAddMoney($user, $data['money']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            } else if ($data['money_status'] == 2) {//减少
                $edit['now_money'] = bcsub($user['now_money'], $data['money'], 2);
                $res1 = UserBillAdmin::expend('系统减少余额', $user['uid'], 'now_money', 'system_sub', $data['money'], $this->adminId, $edit['now_money'], '系统扣除了' . floatval($data['money']) . '余额');
                try {
                    UserRepository::adminSubMoney($user, $data['money']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            }
        } else {
            $res1 = true;
        }
        if ($data['integration_status'] && $data['integration']) {//积分增加或者减少
            if ($data['integration_status'] == 1) {//增加
                $edit['integral'] = bcadd($user['integral'], $data['integration'], 2);
                $res2 = UserBillAdmin::income('系统增加积分', $user['uid'], 'integral', 'system_add', $data['integration'], $this->adminId, $edit['integral'], '系统增加了' . floatval($data['integration']) . '积分');
                try {
                    UserRepository::adminAddIntegral($user, $data['integration']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            } else if ($data['integration_status'] == 2) {//减少
                $edit['integral'] = bcsub($user['integral'], $data['integration'], 2);
                $res2 = UserBillAdmin::expend('系统减少积分', $user['uid'], 'integral', 'system_sub', $data['integration'], $this->adminId, $edit['integral'], '系统扣除了' . floatval($data['integration']) . '积分');
                try {
                    UserRepository::adminSubIntegral($user, $data['integration']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            }
        } else {
            $res2 = true;
        }
        $edit['status'] = $data['status'];
        $edit['real_name'] = $data['real_name'];
        $edit['phone'] = $data['phone'];
        $edit['card_id'] = $data['card_id'];
        $edit['birthday'] = strtotime($data['birthday']);
        $edit['mark'] = $data['mark'];
        $edit['is_promoter'] = $data['is_promoter'];
        if ($edit) $res3 = UserModel::edit($edit, $uid);
        else $res3 = true;
        if ($res1 && $res2 && $res3) $res = true;
        else $res = false;
        BaseModel::checkTrans($res);
        if ($res) return Json::successful('修改成功!');
        else return Json::fail('修改失败');
    }

    /**
     * @title 获取用户的积分以及余额编辑页面
     * @param $uid
     * @return string|void
     * @throws \FormBuilder\exception\FormBuilderException
     */
    public function edit_other($uid)
    {
        if (!$uid) return $this->failed('数据不存在');
        $user = UserModel::get($uid);
        if (!$user) return Json::fail('数据不存在!');
        $f = array();
        $f[] = Form::radio('money_status', '修改余额', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
        $f[] = Form::number('money', '余额')->min(0);
        $f[] = Form::radio('integration_status', '修改积分', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
        $f[] = Form::number('integration', '积分')->min(0);
        $form = Form::make_post_form('修改其他', $f, Url::buildUrl('update_other', array('uid' => $uid)));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    public function update_other($uid = 0)
    {
        $data = Util::postMore([
            ['money_status', 0],
            ['money', 0],
            ['integration_status', 0],
            ['integration', 0],
        ], $this->request);
        if (!$uid) return $this->failed('数据不存在');
        $user = UserModel::get($uid);
        if (!$user) return Json::fail('数据不存在!');
        BaseModel::beginTrans();
        $res1 = false;
        $res2 = false;
        $edit = array();
        if ($data['money_status'] && $data['money']) {//余额增加或者减少
            if ($data['money_status'] == 1) {//增加
                $edit['now_money'] = bcadd($user['now_money'], $data['money'], 2);
                $res1 = UserBillAdmin::income('系统增加余额', $user['uid'], 'now_money', 'system_add', $data['money'], $this->adminId, $edit['now_money'], '系统增加了' . floatval($data['money']) . '余额');
                try {
                    UserRepository::adminAddMoney($user, $data['money']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            } else if ($data['money_status'] == 2) {//减少
                $edit['now_money'] = bcsub($user['now_money'], $data['money'], 2);
                $res1 = UserBillAdmin::expend('系统减少余额', $user['uid'], 'now_money', 'system_sub', $data['money'], $this->adminId, $edit['now_money'], '系统扣除了' . floatval($data['money']) . '余额');
                try {
                    UserRepository::adminSubMoney($user, $data['money']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            }
        } else {
            $res1 = true;
        }
        if ($data['integration_status'] && $data['integration']) {//积分增加或者减少
            if ($data['integration_status'] == 1) {//增加
                $edit['integral'] = bcadd($user['integral'], $data['integration'], 2);
                $res2 = UserBillAdmin::income('系统增加积分', $user['uid'], 'integral', 'system_add', $data['integration'], $this->adminId, $edit['integral'], '系统增加了' . floatval($data['integration']) . '积分');
                try {
                    UserRepository::adminAddIntegral($user, $data['integration']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            } else if ($data['integration_status'] == 2) {//减少
                $edit['integral'] = bcsub($user['integral'], $data['integration'], 2);
                $res2 = UserBillAdmin::expend('系统减少积分', $user['uid'], 'integral', 'system_sub', $data['integration'], $this->adminId, $edit['integral'], '系统扣除了' . floatval($data['integration']) . '积分');
                try {
                    UserRepository::adminSubIntegral($user, $data['integration']);
                } catch (\Exception $e) {
                    BaseModel::rollbackTrans();
                    return Json::fail($e->getMessage());
                }
            }
        } else {
            $res2 = true;
        }
        if ($edit) $res3 = UserModel::edit($edit, $uid);
        else $res3 = true;
        if ($res1 && $res2 && $res3) $res = true;
        else $res = false;
        BaseModel::checkTrans($res);
        if ($res) return Json::successful('修改成功!');
        else return Json::fail('修改失败');
    }
}



